package com.prawn.authority.controller;

import java.io.IOException;
import java.util.*;

import com.prawn.authority.client.traceabilityClient;
import com.prawn.authority.pojo.*;
import com.prawn.authority.pojo.vo.InvitationVo;
import com.prawn.authority.service.*;
import com.prawn.authority.utils.*;
import entity.Base;
import io.swagger.annotations.*;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.web.multipart.MultipartFile;
import util.IdWorker;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 控制器层
 *
 * @author Administrator
 */
@Api(tags = "用户相关接口", description = "提供用户相关的 Rest API")
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {


	@Autowired
	private UserService userService;

	@Autowired
	private EmailService emailService;

	@Autowired
	private JwtUtil jwtUtil;


	@Autowired
	private FastDFSUtil fastDFSUtil;

	@Value("${fdfs.web-server-url}")
	private String fastdfsUrl;

	//默认头像
	@Value("${defaultPhotoUrl}")
	private String defaultPhotoUrl;

	@Autowired
	private CaptchaService captchaService;

	@Autowired
	private traceabilityClient traceabilityClient;

	@Autowired
	private IdWorker idWorker;

	/**
	 * 注册
	 *
	 * @param user
	 * @param code
	 * @return
	 */
	@ApiOperation("用户注册接口")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "code", value = "验证码", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
					"  \"email\": \"123@163.com\",\n" +
					"  \"loginId\": \"40\",\n" +
					"  \"password\": \"40\",\n" +
					"}", required = true, dataType = "User")
	})
	@RequestMapping(value = "/register/{code}", method = RequestMethod.POST)
	public Result register(@RequestBody User user,
						   @PathVariable String code,
						   @RequestParam("captcha") String captcha,
						   HttpServletRequest request) {

		if (!captchaService.checkVerificationCode(request, captcha)) {
			return new Result(false, StatusCode.LOGINERROR, "验证码错误");
		}
		if (!emailService.checkEmailRegisted(user.getEmail())) {
			return new Result(false, StatusCode.ERROR, "该邮箱已注册");
		}
		// 前端通过emailcontroller已经获得了验证码
		// 通过emailservice核对验证码
		if (emailService.checkCode(user.getEmail(), code)) {
			userService.register(user);
			User userByLoginId = userService.findByLoginId(user.getLoginId());
			// photoUrl给了空值，并不会自动分配一个图片url插入数据库，而是插入NULL
			userService.uploadPhoto(userByLoginId.getUserId(), null);
			//验证成功后删除缓存中的验证码
			emailService.deleteCode(user.getEmail());
			return new Result(true, StatusCode.OK, "注册成功");
		} else {
			return new Result(false, StatusCode.ERROR, "验证码错误或已过期");
		}
	}

	/**
	 * 登陆
	 * 参数一：用户登陆用户名和密码的封装对象，
	 * 参数二：用户填写验证码的值
	 * 参数三：request请求，用于获取用户的ip地址，然后通过ip获取redis中的验证码的值
	 * 参数四：response用于通过header相应头将token回写到客户端
	 */
	@ApiOperation("登陆接口")
	@ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
			"  \"loginId\": 123456,\n" +
			"  \"password\": 123456\n" +
			"}", required = true, dataType = "User")
	@PostMapping(value = "/login")
	public Result login(@RequestBody User user,
						@RequestParam("captcha") String captcha,
						HttpServletRequest request,
						HttpServletResponse response) {

		// 判断验证码是否正确，若错误，则没必要再下进行了
		if (!captchaService.checkVerificationCode(request, captcha)) {
			return new Result(false, StatusCode.LOGINERROR, "验证码错误");
		}

		// 调用userService进行逻辑操作进行登陆
		User userLogin = userService.login(user);
		UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userLogin;

		// 如果是管理员，不给登陆
		if (userLogin.getIsAdmin() != 0) {
			return new Result(false, StatusCode.LOGINERROR, "登陆失败");
		}

		String photo = userService.getPhoto(userLogin.getUserId());
		// 用户没有头像，默认给用户设置一个头像
		if (StringUtils.isEmpty(photo)) {
			photo = defaultPhotoUrl;
		}

		// 将用户信息封装到一个map集合返回给前端
		Map<String, Object> map = new HashMap<>();
		map.put("loginId", userLogin.getLoginId());
		map.put("userName", userLogin.getName());
		map.put("photo", photo);
		map.put("role", "user");
		map.put("userId", userDetailsImpl.getUserId());
		map.put("baseId", userDetailsImpl.getBaseId());
		map.put("baseIdentity", userDetailsImpl.getBaseIdentity());
		map.put("merchantId", userDetailsImpl.getMerchantId());

		// 获取jwt来返回给前端
		String token = jwtUtil.createJWT(
				userDetailsImpl.getUserId(),
				userDetailsImpl.getUsername(),
				"user");

		// 把token写入响应体中
		ResponseUtil.placeToken(response, token);

		return new Result(true, StatusCode.OK, "登陆成功", map);
	}

	/**
	 * 增加普通用户
	 *
	 * @param user
	 */
	@ApiOperation("新增普通用户接口")
	@ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
			"  \"baseId\": \"123456\",\n" +
			"  \"baseIdentity\": 1,\n" +
			"  \"*email\": \"1234@163.com\",\n" +
			"  \"*loginId\": \"123456\",\n" +
			"  \"merchantId\": \"123456\",\n" +
			"  \"mobile\": \"13513513513\",\n" +
			"  \"name\": \"张三\",\n" +
			"  \"*password\": \"123456\",\n" +
			"  \"phone\": \"123456789\",\n" +
			"  \"sex\": \"男\"\n" +
			"}", required = true, dataType = "User")
	@PreAuthorize("hasAnyAuthority('authority_user_add')")
	@PostMapping
	public Result add(@RequestBody User user) {
		// 设置为普通用户
		user.setIsAdmin(0);
		// 将用户保存到数据库中
		userService.add(user);
		// 添加头像（由于是后面扩充的内容，数据库采取添加一张表，而不是增加一个字段，所以才有了以下两步操作）
		User userByLoginId = userService.findByLoginId(user.getLoginId());
		userService.uploadPhoto(userByLoginId.getUserId(), null);
		return new Result(true, StatusCode.OK, "增加成功");
	}


	/**
	 * 查询全部用户数据
	 *
	 * @return
	 */
	@ApiOperation("查询所有普通用户接口")
	@PreAuthorize("hasAnyAuthority('authority')")
	@RequestMapping(method = RequestMethod.GET)
	public Result findAllUser() {
		return new Result(true, StatusCode.OK, "查询成功", userService.findAllUser());
	}


	/**
	 * 根据ID查询用户
	 *
	 * @param id ID
	 * @return
	 */
	@ApiImplicitParam(paramType = "path", name = "id", value = "登录ID", required = true, dataType = "String")
	@ApiOperation("根据id查询普通用户接口")
	@PreAuthorize("hasAnyAuthority('authority')")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Result findById(@PathVariable String id) {
		return new Result(true, StatusCode.OK, "查询成功", userService.findUserByUserId(id));
	}

	/**
	 * 分页+多条件查询普通用户
	 *
	 * @param searchMap 查询条件封装
	 * @param page      页码
	 * @param size      页大小
	 * @return 分页结果
	 */
	@ApiOperation("分页加条件查询接口")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
			@ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer"),
			@ApiImplicitParam(paramType = "body", name = "searchMap", value = "{\n" +
					"\t\t\"baseId\": \"123456\",\n" +
					"\t\t\t\t\"baseIdentity\": 1,\n" +
					"\t\t\t\t\"email\": \"123@163.com\",\n" +
					"\t\t\t\t\"loginId\": \"123456\",\n" +
					"\t\t\t\t\"merchantId\": \"123456\",\n" +
					"\t\t\t\t\"mobile\": \"13513513513\",\n" +
					"\t\t\t\t\"name\": \"张三\",\n" +
					"\t\t\t\t\"phone\": \"12345678\",\n" +
					"\t\t\t\t\"sex\": \"男\"\n" +
					"\t}", required = true, dataType = "User")
	})
	@PreAuthorize("hasAnyAuthority('authority')")
	@RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
		searchMap.put("isAdmin", 0);
		Page<User> pageList = userService.findSearchUser(searchMap, page, size, "0");
		return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
	}

	/**
	 * 根据条件查询
	 *
	 * @param searchMap
	 * @return
	 */
	@ApiOperation("条件查询接口")
	@ApiImplicitParam(paramType = "body", name = "searchMap", value = "{\n" +
			"\t\t\"baseId\": \"123456\",\n" +
			"\t\t\t\t\"baseIdentity\": 1,\n" +
			"\t\t\t\t\"email\": \"123@163.com\",\n" +
			"\t\t\t\t\"loginId\": \"123456\",\n" +
			"\t\t\t\t\"merchantId\": \"123456\",\n" +
			"\t\t\t\t\"mobile\": \"13513513513\",\n" +
			"\t\t\t\t\"name\": \"张三\",\n" +
			"\t\t\t\t\"phone\": \"12345678\",\n" +
			"\t\t\t\t\"sex\": \"男\"\n" +
			"\t}", required = true, dataType = "User")
	@PreAuthorize("hasAnyAuthority('authority')")
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap) {
		return new Result(true, StatusCode.OK, "查询成功", userService.findSearchUser(searchMap, "0"));
	}

	/**
	 * 用户查看自己信息接口
	 */
	@ApiOperation("用户查询自己信息接口")
	@RequestMapping(value = "/self", method = RequestMethod.GET)
	public Result findSelf() {
		// 获取用户的信息
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		return new Result(true, StatusCode.OK, "查询成功", userService.findUserByUserId(user.getUserId()));
	}

	/**
	 * 修改
	 *
	 * @param user
	 */
	@ApiOperation("用户修改自己接口")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "String"),
	})
	@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
	public Result update(@RequestBody User user, @PathVariable String id) {
		UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();

		if (!id.equals(userDetails.getUserId())) {
			return new Result(false, StatusCode.ERROR, "用户只能修改自己的信息");
		}

		//防止用户非法修改账号的养殖基地信息和店铺信息
		User loginUser = userService.findUserByUserId(id);
		user.setBaseId(loginUser.getBaseId());
		user.setBaseIdentity(loginUser.getBaseIdentity());
		user.setMerchantId(loginUser.getMerchantId());
		user.setUserId(id);
		userService.updateUser(user, 0);
		return new Result(true, StatusCode.OK, "修改成功");
	}

	@ApiOperation("管理员修改用户接口")
	@ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "String")
	@PreAuthorize("hasAnyAuthority('authority_user_update')")
	@RequestMapping(value = "/admin/{id}", method = RequestMethod.PUT)
	public Result updateUser(@RequestBody User user, @PathVariable String id) {
		user.setUserId(id);
		userService.updateUser(user, 0);
		return new Result(true, StatusCode.OK, "修改成功");
	}

	/**
	 * 删除
	 *
	 * @param id
	 */
	@ApiOperation("删除用户接口")
	@ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "String")
	@PreAuthorize("hasAnyAuthority('authority_user_delete')")
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public Result delete(@PathVariable String id) {
		try {
			// 134.175.208.235
			int begin = fastdfsUrl.length() + 8 - 1;
			String photo = userService.getPhoto(id);
			String deleteUrl = photo.substring(begin);
			fastDFSUtil.deleteFile(deleteUrl);
		} catch (NullPointerException e) {
		}
		userService.delUserAndPhoto(id);
		userService.deleteUserById(id, 0);

		return new Result(true, StatusCode.OK, "删除成功");
	}

	/**
	 * 找回密码
	 *
	 * @param code
	 * @param user
	 * @return
	 */
	@ApiOperation("找回密码接口")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "code", value = "验证码", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
					"  \"email\": \"123@163.com\",\n" +
					"  \"loginId\": \"123456\",\n" +
					"  \"password\": \"123456\"\n" +
					"}", required = true, dataType = "User")
	})
	@RequestMapping(value = "/retrievePassword/{code}", method = RequestMethod.POST)
	public Result retrievePassword(@PathVariable String code,
								   @RequestBody User user,
								   @RequestParam("captcha") String captcha,
								   HttpServletRequest request
	) {

		if (!captchaService.checkVerificationCode(request, captcha)) {
			return new Result(false, StatusCode.LOGINERROR, "验证码错误");
		}
		if (emailService.checkCode(user.getEmail(), code)) {
			// 1、需要判断用户输入的用户名是否存在
			// 2、需要判断用户名和邮箱是否对应的上，防止用户非法修改别人的密码
			User userInDB = userService.findByLoginId(user.getLoginId());
			if (userInDB == null || !userInDB.getEmail().equals(user.getEmail())) {
				return new Result(false, StatusCode.ERROR, "密码修改失败，请检查账号和邮箱是否正确");
			}

			// 修改用户的密码
			userInDB.setPassword(user.getPassword());
			userService.updateUser(userInDB, userInDB.getIsAdmin());
			// 验证成功后删除缓存中的验证码
			emailService.deleteCode(user.getEmail());
			return new Result(true, StatusCode.OK, "密码修改成功");
		} else {
			return new Result(false, StatusCode.ERROR, "验证码错误或已过期");
		}
	}

	/**
	 * 用户申请变更基地管理员权限
	 *
	 * @param baseId
	 * @return
	 */
	@ApiOperation("用户申请变更基地管理员权限")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "baseId", value = "基地id", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "path", name = "baseIdentity", value = "权限", dataType = "Integer")
	})
	@RequestMapping(value = "/applyFor/{baseId}/{baseIdentity}", method = RequestMethod.PUT)
	public Result applyForBaseAdmin(@PathVariable String baseId, @PathVariable int baseIdentity) {
		if (baseIdentity != 0 && baseIdentity != 1) {
			return new Result(false, StatusCode.ERROR, "权限错误");
		}
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		userService.applyForBaseAdmin(user.getUserId(), baseId, baseIdentity);

		return new Result(true, StatusCode.OK, "申请成功");
	}

	/**
	 * 用户查看申请变更基地管理员的处理状态
	 *
	 * @return
	 */
	@ApiOperation("用户查看申请变更基地管理员的处理状态")
	@RequestMapping(value = "/applyFor", method = RequestMethod.GET)
	public Result applyForStatus() {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		Map<String, String> map = userService.applyForStatus(user.getUserId());
		if (map == null) {
			return new Result(true, StatusCode.OK, "已处理");
		} else {
			return new Result(true, StatusCode.OK, "未处理", map);
		}
	}

	/**
	 * 用户申请新建基地
	 *
	 * @param base
	 * @return
	 */
	@ApiOperation("用户申请新建基地")
	@Transactional
	@ApiImplicitParam(paramType = "body", name = "base", value = "{\n" +
			"\t\t\"baseName\": \"123456\",\n" +
			"\t\t\t\t\"registNumber\": \"string\"\n" +
			"\t}", required = true, dataType = "Base")
	@RequestMapping(value = "applyFor/addBase", method = RequestMethod.PUT)
	public Result applyForAddBase(@RequestBody Base base) {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		base.setCreateBy(user.getName());
		String baseId = idWorker.nextId() + "";
		base.setId(baseId);
		userService.applyForAddBase(user.getUserId(), base);

		return new Result(true, StatusCode.OK, "申请成功");
	}

	/**
	 * 用户查看申请新建基地的处理状态
	 *
	 * @return
	 */
	@ApiOperation("用户查看申请新建基地的处理状态")
	@RequestMapping(value = "applyFor/addBase/status", method = RequestMethod.GET)
	public Result applyForAddBaseStatus() {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		Base base = userService.applyForAddBaseStatus(user.getUserId());
		if (base == null) {
			String baseId = userService.getBase(user.getUserId()).get("baseId");
			Object base1 = traceabilityClient.getBase(baseId).getData();
			return new Result(true, StatusCode.OK, base1 == null ? "拒绝" : "同意", base1);
		} else {
			return new Result(true, StatusCode.OK, "未处理", base);
		}
	}

	/**
	 * 获取自己的头像
	 */
	@ApiOperation(value = "获取头像")
	@RequestMapping(value = "/getPhoto", method = RequestMethod.GET)
	public Result getPhoto() {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		String photo = userService.getPhoto(user.getUserId());
		if (photo == null || "".equals(photo)) {
			photo = defaultPhotoUrl;
		}
		return new Result(true, StatusCode.OK, "查询头像成功", photo);
	}

	/**
	 * 根据id集合获取头像
	 *
	 * @param userIds
	 * @return
	 */
	@ApiOperation(value = "根据id集合获取头像")
	@RequestMapping(value = "/getPhotoByIds", method = RequestMethod.POST)
	public Result getPhotoByIdArray(@RequestParam List<String> userIds) {
		Map<String, String> photos = new HashMap<>();
		String photo;

		for (String userId : userIds) {
			photo = userService.getPhoto(userId);
			if (photo == null || "".equals(photo)) {
				photo = defaultPhotoUrl;
			}
			photos.put(userId, photo);
		}
		return new Result(true, StatusCode.OK, "查询头像成功", photos);
	}

	/**
	 * 更换头像
	 *
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@ApiOperation(value = "更换头像")
	@RequestMapping(value = "/updatePhoto", method = RequestMethod.POST)
	public Result updatePhoto(@RequestParam("file") MultipartFile file) throws IOException {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		try {
			String photo = userService.getPhoto(user.getUserId());
			if (photo == null || "".equals(photo)) {
			} else {
				int begin = fastdfsUrl.length() + 8 - 1;
				String deleteUrl = photo.substring(begin);
				fastDFSUtil.deleteFile(deleteUrl);
			}
		} catch (NullPointerException e) {
		}
		String url = fastDFSUtil.uploadFile(file);
		userService.updatePhoto(user.getUserId(), url);
		return new Result(true, StatusCode.OK, "修改成功");
	}

	/**
	 * 删除头像
	 *
	 * @param
	 * @return
	 * @throws IOException
	 */
	@ApiOperation(value = "删除自己头像")
	@RequestMapping(value = "/deletePhoto", method = RequestMethod.DELETE)
	public Result deletePhoto() {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		try {
			int begin = fastdfsUrl.length() + 8 - 1;
			String photo = userService.getPhoto(user.getUserId());
			if (photo == null || "".equals(photo)) {
				return new Result(false, StatusCode.ERROR, "默认头像不能删除");
			}
			String deleteUrl = photo.substring(begin);
			fastDFSUtil.deleteFile(deleteUrl);
		} catch (NullPointerException e) {
		}
		userService.delPhoto(user.getUserId());
		return new Result(true, StatusCode.OK, "删除成功");
	}

	@ApiOperation(value = "用户获取自己的基地身份")
	@RequestMapping(value = "/getBase", method = RequestMethod.GET)
	public Result getBaseIdentity() {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		HashMap<String, String> base = userService.getBase(user.getUserId());
		if (base == null || "".equals(base)) {
			return new Result(false, StatusCode.ERROR, "用户基地信息为空");
		} else {
			return new Result(true, StatusCode.OK, "查询成功", base);
		}
	}


	@ApiOperation(value = "用户获取自己的店铺信息")
	@RequestMapping(value = "/getMerchant", method = RequestMethod.GET)
	public Result getMerchant() {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		HashMap<String, String> map = userService.getMerchant(user.getUserId());
		if (map == null || "".equals(map)) {
			return new Result(false, StatusCode.ERROR, "用户店铺信息为空");
		} else {
			return new Result(true, StatusCode.OK, "查询成功", map);
		}
	}

	@ApiOperation(value = "用户修改自己的邮箱")
	@RequestMapping(value = "/setEmail", method = RequestMethod.POST)
	public Result setEmail(String addr, String code) {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		User user1 = new User();
		if (emailService.checkCode(addr, code)) {
			//验证成功后删除缓存中的验证码
			emailService.deleteCode(addr);
			try {
				user1.setEmail(addr);
				user1.setUserId(user.getUserId());
				userService.updateUser(user1, 0);
			} catch (Exception e) {
				throw new GlobalException(new Result(false, StatusCode.ERROR, "更新邮箱失败," + e.getMessage()));
			}
			return new Result(true, StatusCode.OK, "邮箱修改成功");
		} else return new Result(false, StatusCode.ERROR, "验证码错误");
	}


	@ApiOperation(value = "获取用户自己的基地信息")
	@RequestMapping(value = "/base", method = RequestMethod.GET)
	public Result getBase() {
		UserDetailsImpl user = SecurityContextUtil.getUserDetails();
		HashMap<String, String> base = userService.getBase(user.getUserId());
		System.out.println(base.get("baseId"));
		return traceabilityClient.getBase(base.get("baseId"));
	}

	/**
	 * 获取所有目前没有进基地的用户
	 *
	 * @return
	 */
	@ApiOperation(value = "获取所有未进基地的用户")
	@GetMapping("/getAllNoBaseUser")
	public Result getAllNoBaseUser() {
		return Result.success("查询成功", userService.listNoBaseUser());
	}


	/**
	 * 多条件查询没有进基地的用户
	 *
	 * @param searchMap
	 * @return
	 */
	@ApiOperation("多条件查询没有进基地的用户")
	@PostMapping("/getNoBaseUser")
	public Result getNoBaseUserByCondition(@RequestBody @ApiParam(name = "搜索条件", value = "传入Json格式",required = true) Map<String,String> searchMap) {
		List<User> userList = userService.listNoBaseUser(searchMap);
		return Result.success("查询成功", userList);
	}

	/**
	 * 分页+多条件查询没有进基地的用户
	 *
	 * @param searchMap
	 * @param page
	 * @param size
	 * @return
	 */
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
			@ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer"),
	})
	@ApiOperation("(分页+多条件)查询未进基地的用户")
	@PostMapping("/searchNoBaseUser/{page}/{size}")
	public Result pageListNoBaseUser(@RequestBody @ApiParam(name = "搜索条件", value = "传入json格式（不传等于，分页查询所有未进入基地的用户）") Map searchMap, @PathVariable int page, @PathVariable int size) {
		// 添加条件，没有基地的用户
		Page<User> pageList = userService.pageListNoBaseUser(searchMap, page, size);
		return Result.success("查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
	}

	/**
	 * 基地管理人员邀请用户进基地
	 *
	 * @param userId
	 * @return
	 */
	@ApiOperation("邀请还没有进基地的用户进入基地")
	@GetMapping("/invite/{userId}")
	@PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
	public Result inviteUser(@ApiParam(value = "UserID", required = true) @PathVariable(name = "userId") String userId) {
		UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
		String baseId = userService.findUserByUserId(userDetails.getUserId()).getBaseId();
		userService.inviteUserIntoBase(userId, baseId);
		return Result.success("发送邀请成功");
	}

	/**
	 * 基地分页获取所有已邀请过的用户记录
	 * 显示三种状态，待确认(2)，已拒绝(0)，已同意(1)
	 *
	 * @return
	 */
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
			@ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
	})
	@ApiOperation("基地分页查询已邀请的用户的结果,（通过status来判断，0表示已拒绝，1表示已同意，2表示待确认）")
	@GetMapping("/getUserInvited/{page}/{size}")
	@PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
	public Result getAllUserInvited(@PathVariable(name = "page") Integer page, @PathVariable(name = "size") Integer size) {
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		String baseId = userService.findUserByUserId(userId).getBaseId();
		List<InvitationVo> invitationVoList = userService.getInvitationRecord(baseId);
		PageResult<InvitationVo> pageResult = PageUtil.getPage(invitationVoList, page, size);
		return Result.success("查询成功", pageResult);
	}


	/**
	 * 基地分页获取指定状态的邀请记录
	 *
	 * @param typeId
	 * @return
	 */
	@ApiOperation("基地分页获取指定状态的邀请记录")
	@GetMapping("/getTypeInvitation/{typeId}/{page}/{size}")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "typeId", value = "邀请状态类型ID", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer", required = true),
			@ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer", required = true)
	})
	@PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
	public Result getUserInvitedByTypeId(@PathVariable(name = "typeId", required = true) String typeId, @PathVariable(name = "page", required = true) Integer page, @PathVariable(name = "size", required = true) Integer size) {
		if (StringUtils.isEmpty(typeId)
				|| (!typeId.equals("2")
				&& !typeId.equals("1")
				&& !typeId.equals("0"))) {
			throw new GlobalException(Result.error(StatusCode.ERROR, "传入的typeId有误"));
		}
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		String baseId = userService.findUserByUserId(userId).getBaseId();
		List<User> typeInvitationRecord = userService.getTypeInvitationRecord(baseId, typeId);
		PageResult<User> pageResult = (PageResult<User>) PageUtil.getPage(typeInvitationRecord, page, size);
		return Result.success("查询成功", pageResult);
	}

	/**
	 * 用户分页查看自己被哪些基地邀请
	 *
	 * @return
	 */
	@ApiOperation("用户分页查看自己被哪些基地邀请")
	@GetMapping("/invitation/{page}/{size}")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
			@ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
	})
	public Result findAllInvitation(@PathVariable(name = "page") Integer page, @PathVariable(name = "size") Integer size) {
		// 获取当前用户的信息，主要为了后续获取userId
		UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
		// 通过loginId获取用户被哪些基地邀请
		List<Map<String, String>> baseInfoList = userService.findAllInvitation(userDetails.getUserId());
		PageResult<Map<String, String>> pageResult = PageUtil.getPage(baseInfoList, page, size);
		return Result.success("查询成功", pageResult);
	}

	/**
	 * 用户同意（拒绝）进某个基地
	 * 同意（1），拒绝（0）
	 *
	 * @param selection
	 * @param baseId
	 * @return
	 */
	@ApiOperation("用户同意（拒绝）进某个基地")
	@PutMapping("/invitation/{baseId}/{selection}")
	public Result executeSelection(@ApiParam(value = "同意（1），拒绝（0）", required = true) @PathVariable(name = "selection") String selection, @ApiParam(value = "基地ID", required = true) @PathVariable(name = "baseId") String baseId) {
		if (!"0".equals(selection) && !"1".equals(selection)) {
			return Result.error(StatusCode.ERROR, "选择无效");
		}
		// 获取当前用户
		UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
		// 通过loginId、baseId、selection来进行执行这个选择
		userService.executeSelection(userDetails.getUserId(), baseId, selection);
		return Result.success("选择成功");
	}

	/**
	 * 基地删除所有的邀请记录（包含待确认、同意、拒绝）
	 *
	 * @return
	 */
	@ApiOperation("基地删除所有邀请记录（包含待确认、同意、拒绝）")
	@DeleteMapping("/deleteInvitationRecord")
	@PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
	public Result deleteInvitationRecord() {
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		String baseId = userService.findUserByUserId(userId).getBaseId();
		userService.deleteInvitationRecordByBaseId(baseId);
		return Result.success("删除成功");
	}

	/**
	 * 基地删除指定类型的邀请记录
	 * 三种类型：同意、拒绝、待确认
	 *
	 * @param typeId
	 * @return
	 */
	@ApiOperation("基地删除指定类型的邀请记录")
	@DeleteMapping("/deleteInvitationRecord/{typeId}")
	@PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
	public Result deleteTypeInvitationRecord(@ApiParam(name = "typeId", value = "（2）待确认，（1）同意，（0）拒绝", required = true) @PathVariable(name = "typeId", required = true) String typeId) {
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		String baseId = userService.findUserByUserId(userId).getBaseId();
		userService.deleteTypeInvitationRecord(baseId, typeId);
		return Result.success("删除成功");
	}

	@ApiOperation("基地删除指定某一条邀请记录")
	@DeleteMapping("/deleteInvitationRecordByUserId/{typeId}/{userId}")
	public Result deleteInvitationRecordByUserId(@ApiParam(name = "typeId", value = "记录类型ID（0、1、2）", required = true) @PathVariable(name = "typeId", required = true) String typeId, @ApiParam(name = "userId", value = "用户ID", required = true) @PathVariable(name = "userId", required = true) String userId) {
		String adminUserId = SecurityContextUtil.getUserDetails().getUserId();
		String baseId = userService.findUserByUserId(adminUserId).getBaseId();
		userService.deleteInvitationRecordByUserId(userId, baseId, typeId);
		return Result.success("删除成功");
	}

	/**
	 * 用户删除所有基地的邀请
	 *
	 * @return
	 */
	@ApiOperation("用户删除所有基地的邀请")
	@DeleteMapping("/deleteAllInvitation")
	public Result deleteAllInvitation() {
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		userService.deleteAllInvitation(userId);
		return Result.success("删除成功");
	}

	/**
	 * 用户删除指定基地的邀请
	 *
	 * @param baseId
	 * @return
	 */
	@ApiOperation("用户删除指定基地的邀请")
	@DeleteMapping("/deleteAllInvitation/{baseId}")
	public Result deleteInvitationByBaseId(@ApiParam(name = "baseId", value = "基地ID", required = true) @PathVariable(value = "baseId", required = true) String baseId) {
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		userService.deleteInvitationByBaseId(userId, baseId);
		return Result.success("删除成功");
	}


	/**
	 * 通过baseId查询基地内的所有用户
	 *
	 * @return
	 */
	@ApiOperation(value = "查询基地内的所有用户")
	@PreAuthorize("hasAnyAuthority('authority_user_select')")
	@RequestMapping(value = "/getBaseUsers/{page}/{size}", method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
			@ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
	})
	public Result getUserByBaseId(@PathVariable Integer page, @PathVariable Integer size) {
		UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
		//传入老板id查询基地用户
		List<User> users = userService.getUserByUserId(userDetails.getUserId());
		PageResult<User> pageResult = PageUtil.getPage(users, page, size);
		return new Result(true, StatusCode.OK, "获取成功", pageResult);
	}


	/**
	 * 老板更改用户在基地内的身份
	 *
	 * @param userId
	 * @param baseIdentity
	 * @return
	 */
	@ApiOperation("老板更改用户在基地内的身份")
	@PreAuthorize("hasAnyAuthority('authority_role_update')")
	@RequestMapping(value = "/update/{userId}/{baseIdentity}", method = RequestMethod.PUT)
	public Result updateBaseRole(@PathVariable String userId, @PathVariable Integer baseIdentity) {
		userService.updateBaseIdentityOfUser(userId, baseIdentity);
		return new Result(true, StatusCode.OK, "修改角色成功");
	}

	/**
	 * 分页查询基地人员信息（不包含自身）
	 *
	 * @param page
	 * @param size
	 * @return
	 */
	@ApiOperation("分页查询基地人员信息（不包含自身）")
	@GetMapping("/getBaseMember/{page}/{size}")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
			@ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
	})
	public Result pageBaseMember(@PathVariable(name = "page") Integer page, @PathVariable(name = "size") Integer size) {
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		String baseId = userService.findUserByUserId(userId).getBaseId();
		if (baseId == null) {
			return Result.error(StatusCode.ERROR, "查询失败");
		}
		List<User> baseMemberList = userService.getBaseMemberList(userId, baseId);
		return Result.success("查询成功", PageUtil.getPage(baseMemberList, page, size));
	}

	/**
	 * 查询基地人员信息（不包含自身）
	 *
	 * @return
	 */
	@ApiOperation("查询基地人员信息（不包含自身）")
	@GetMapping("/getBaseMember")
	public Result pageBaseMember() {
		String userId = SecurityContextUtil.getUserDetails().getUserId();
		String baseId = userService.findUserByUserId(userId).getBaseId();
		if (baseId == null) {
			return Result.error(StatusCode.ERROR, "查询失败");
		}
		List<User> baseMemberList = userService.getBaseMemberList(userId, baseId);
		return Result.success("查询成功", baseMemberList);
	}

	/**
	 * 基地解雇员工
	 *
	 * @param userId
	 * @return
	 */
	@ApiOperation("基地解雇员工")
	@PutMapping("/sack/{userId}")
	@ApiImplicitParam(paramType = "path", name = "userId", value = "用户ID", dataType = "String")
	@PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
	public Result sackBaseMember(@PathVariable(name = "userId") String userId) {
		String uid = SecurityContextUtil.getUserDetails().getUserId();
		User user = userService.findUserByUserId(uid);
		String baseId = user.getBaseId();
		Integer baseIdentity = user.getBaseIdentity();
		userService.sackEmployeeByUserIdAndBaseId(userId, baseId, baseIdentity);
		return Result.success("解雇成功");
	}

}